/*
 * @Description: 国际化入口
 * @Version: 2.0
 * @Autor: lhl
 * @Date: 2021-08-21 19:07:52
 * @LastEditors: lhl
 * @LastEditTime: 2021-08-22 11:04:32
 */
import Vue from "vue";
import VueI18n from "vue-i18n";

import { getLanguage } from "Utils/cookies";

// Vant built-in lang
import { Locale } from "vant";
import enUS from "vant/es/locale/lang/en-US";
import zhCN from "vant/es/locale/lang/zh-CN";
import zhTW from "vant/es/locale/lang/zh-TW";
import jaJP from "vant/es/locale/lang/ja-JP";

// User defined lang
import enUsLocale from "./en_US";
import zhCnLocale from "./zh_CN";
import zhTwLocale from "./zh_TW";
import jaJpLocale from "./ja_JP";

Vue.use(VueI18n);

const messages = {
  "zh-CN": {
    ...zhCN,
    ...zhCnLocale,
  },
  "zh-TW": {
    ...zhTW,
    ...zhTwLocale,
  },
  "en-US": {
    ...enUS,
    ...enUsLocale,
  },
  "ja-JP": {
    ...jaJP,
    ...jaJpLocale,
  },
};

export const getLocale = () => {
  const cookieLanguage = getLanguage();
  if (cookieLanguage) {
    document.documentElement.lang = cookieLanguage;
    return cookieLanguage;
  }

  const language = navigator.language.toLowerCase();
  const locales = Object.keys(messages);
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      document.documentElement.lang = locale;
      return locale;
    }
  }

  // Default language is english
  return "en-US";
};

const CURRENT_LANG = getLocale();
console.log(CURRENT_LANG, "CURRENT_LANG");

// first entry
Locale.use(CURRENT_LANG, messages[CURRENT_LANG]);

const i18n = new VueI18n({
  locale: CURRENT_LANG,
  messages,
  silentTranslationWarn: true, // 去除警告
});

export default i18n;
